<template>
  <div class="app-container">
    <Progress :newStep="param.newStep" />
    <el-row :gutter="20">
      <el-col :span="18">
        <el-card class="marginTop20">
          <el-row>
              <el-col :span="14" :align="'left'">
                <span style="font-size: 16px;font-weight: 600;">{{ rowData.companyName }}</span>
              </el-col>
              <el-col :span="10" :align="'right'">
                  <el-button type="primary" link plain icon="ChatDotSquare">联系客服</el-button>
              </el-col>
          </el-row>
          <el-row :gutter="40" class="marginTop20">
              <el-col :span="11"><Carousel v-bind="swiperData" ></Carousel></el-col>
              <el-col :span="12">
                <el-row>
                  <el-col :span="24" style="font-size: 18px;font-weight: 700;">{{ rowData.carryCityName }}</el-col>
                  <el-col :span="24">购箱城市:{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5" class="marginTop10">购箱单价</el-col> <el-col :span="18" class="marginTop10" style="color: #ff0000;">{{param.currencyStr}}{{ Number(param.unitPrice).toLocaleString() }}</el-col>
                  <!-- <el-col :span="5" class="marginTop10">结算币种:</el-col> <el-col :span="18" class="marginTop10">{{{'USD':'美元','CNY':'人民币','CNY,USD':'人民币,美元','USD,CNY':'美元,人民币'}[param.payCurrency]}}</el-col> -->
                  <el-col :span="5" class="marginTop10">箱况</el-col> <el-col :span="18" class="marginTop10">{{ boxConditionFilter(param.boxCondition) }}</el-col>
                  <el-col :span="5" class="marginTop10">箱型</el-col> <el-col :span="18" class="marginTop10">{{ boxTypeFilter(param.boxType) }}</el-col>
                  <el-col :span="5" class="marginTop10">箱量</el-col> <el-col :span="18" class="marginTop10"> 
                    <el-input-number v-model="param.num" :min="0"  @change="handleChange" @blur="validateNumber" />
                  </el-col>
                </el-row>
              </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="pag-container" style="height: 378px; ">
          <span class="_before">购箱费用</span>
          <table
            style="font-size: 14px;width: 400px;margin-top: 20px;width:100%;border-collapse:separate; border-spacing:0px 10px;">
            <!-- <tr style="width: 100px;">
              <td style="width:100px; ">箱型/箱况</td>
              <td align="right">{{ boxTypeFilter(param.boxType) }} / {{ boxConditionFilter(param.boxCondition) }}</td>
            </tr>
            <tr>
              <td>购箱单价</td>
              <td align="right">￥{{ param.unitPrice || 0 }}</td>
            </tr>
            <tr>
              <td>购箱数量</td>
              <td align="right" style="color: red;">{{ param.num || 0 }}</td>
            </tr> -->
        <tbody>
            <tr>
              <td>购箱金额</td>
              <td align="right" style="color: red;">{{param.currencyStr}}{{ numMulti(param.unitPrice, param.num) || 0 }}</td>
            </tr>
            <tr>
              <td>优惠券</td>
              <td align="right"> <el-select style="width:150px"></el-select> </td>
            </tr>
            </tbody>
          </table>
          <div style="margin-top: 50px;">
            <div style="border-bottom:3px Dotted  #999999; width: 100%;"></div>
            <table style="width:100%">
        <tbody>
              <tr>
                <td style="width:100px; ">合计</td>
                <td align="right" style="color: red;">{{param.currencyStr}}{{ numMulti(param.unitPrice, param.num) || 0 }}</td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="pag-container">
      <span class="_before">订单信息</span>
      <orderInfoForm ref="infoFormRef" :orderInfo="orderInfoData"></orderInfoForm>
    </el-card>

    <el-card class="pag-container">
      <orderAllocation ref="allocationRef"  ></orderAllocation>
    </el-card>

    <el-row style="width:100%;text-align: center;margin-top: 30px;">
      <div style="width:100%;text-align: center;">
        <el-checkbox v-model="checkval" />我已阅读<span @click="showRules(1)">《集装箱租赁业务规则》</span>、<span @click="showRules(2)">《用户服务协议和管理规则》</span>并同意全部条款
        <el-button  @click="handleSubmit" type="primary">提交订单</el-button>
      </div>
    </el-row>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" width="500">
      <div v-if="param.isHandleSigned">
        <div style="width: 100%;text-align: center;">
          <el-icon style="color: green;">
            <SuccessFilled />
          </el-icon>
          <div style="color:#212121;font-size: 18px;margin-top: 10px">E签宝协议已发送</div>
          <div><el-button type="primary" style="margin-top: 10px" @click="handleClose">关闭</el-button>
          </div>
        </div>
      </div>
      <div v-else>
        <el-form :model="param">
          <el-form-item label="签署人姓名">
            <el-input v-model="param.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="签署人电话">
            <el-input v-model="param.code" placeholder="请输入验证码" />
          </el-form-item>
          <el-form-item>
            <div style="background-color: #FFF2E7;padding: 5px;box-sizing: border-box;width: 100%">
              <el-icon style="color: #2158F3;">
                <WarningFilled />
              </el-icon> 请确认签署人是否正确，更改签署人将重新发起签署！<br>
              <a href="#" style="padding-left: 20px;color: #7CAFFF;">E签宝协议签订教程</a>
            </div>
          </el-form-item>
        </el-form>
        <div style="text-align: center;">
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
          <el-button @click="handleSign">确认</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 规则弹窗 -->
    <el-dialog v-model="rulesInfo.dialogRules">
        <BusinessRules1 v-if="rulesInfo.rules1"></BusinessRules1>
        <BusinessRules2 v-if="rulesInfo.rules2"></BusinessRules2>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rulesInfo.dialogRules = false">关闭</el-button>
          </div>
        </template>
    </el-dialog>

  </div>
</template>
<script lang="ts" setup>
import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Progress from '@/components/progress/index.vue'
import orderInfo from '@/store/modules/order'
import  Carousel from '@/components/carousel'
import orderInfoForm from '@/views/components/purchaseBox/orderInfoForm'
import orderAllocation from '@/views/components/purchaseBox/orderAllocation'
import { addPurchaseBoxOrder } from '@/api/boxDeal/boxBuy'
import  BusinessRules1 from '@/components/protocolRegulations/businessRules1'
import  BusinessRules2 from '@/components/protocolRegulations/businessRules2'
import { numAdd, numSub, numMulti } from '@/utils/compute'
import { getReleaseSalesInfo } from '@/api/boxDeal/boxSeel'
import { ElMessage, anchorProps } from 'element-plus';


const router = useRouter()
const route = useRoute()
const param = reactive({
  payCurrency: "",
  dialogVisible: false,
  isHandleSigned: false,
  boxConditionList: [],
  boxTypeList: [],
  boxType: '',
  boxCondition: '',
  num: 0,
  page: 1,
  limit: 10,
  newStep: 1,

  //订单分配 
  // operateUsers: [],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  // businessUser: '',
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  // businessNo: '',
  allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }],
  // form0: { 'operateUsers': [3, 5], "businessUser": 2, "businessNo": "NO1234567890" },
  unitPrice: "",
  inventory: "",
  currency:'',
  currencyStr:''

})

const checkval = ref(false)
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"450px"
  }
})


const inventory = computed(() => {
  let tagDataList = rowData.value.releaseRentPriceList
  let num = 0
  if (!tagDataList) return 0
  tagDataList.forEach((item: any) => {
    if (item.boxType == param.boxType && item.boxCondition == param.boxCondition) {
      num = item.inventory
    }
  })
  param.inventory = num - param.num
  return num - param.num
})

onActivated(() => {
  getSetBoxInfo()
  param.isHandleSigned = false
})

const allocationRef = ref()
const infoFormRef = ref({ formData: {}, onSubmit: () => { } })
const orderInfoData = ref()


// 获取数据
const mainFileList = ref([])
const rowData = ref([])
const getSetBoxInfo = () => {
  const row = orderInfo().rowData
  orderInfoData.value = row
  if (row) {
    const result = row
    orderInfoData.value = result
    rowData.value = result
    param.newStep = result?.status
    mainFileList.value = JSON.parse(result.mainFileList)
    swiperData.list = JSON.parse(result.mainFileList)
    // detailFileList.value = JSON.parse(result.detailFileList)
    // const data = row.submitData
    if(row?.submitData){//详情
      setBoxInfo(row?.submitData)
    }else{//列表
      getSetBoxInfoDetai()
    }
  }
}
const getSetBoxInfoDetai = async () => {
  const row = orderInfo().rowData
  if (row) {
    await getReleaseSalesInfo(row.releaseSaleId).then((res: any) => {
      const result = res.data
      mainFileList.value = JSON.parse(result.mainFileList)
      rowData.value = result
      if(result.releaseSalePriceList){
        let dataInfo=result.releaseSalePriceList[0]
        param.boxType = dataInfo.boxType
        param.boxCondition = dataInfo.boxCondition
        param.num = 0
        param.unitPrice = dataInfo.unitPrice
        param.inventory = dataInfo.inventory
        param.payCurrency = dataInfo.currency
        param.currency = dataInfo.currency
        param.currencyStr = dataInfo.currency == "USD" ?  '$' : '￥'
      }
    })
  }
}
// 
const setBoxInfo = (data: any) => {
  param.boxType = data.boxType
  param.boxCondition = data.boxCondition
  param.num = data.num
  param.unitPrice = data.unitPrice
  param.inventory = data.inventory
  param.payCurrency = data.payCurrency
  param.currency = data.currency
  param.currencyStr = data.currency == "USD" ?  '$' : '￥'
}

//
// const handleChange = (value: Number) => {
//   console.log(value)
//   if (!inventory) {

//   }
// }
const handleClose = () => {
  param.isHandleSigned = false
  param.dialogVisible = false
}

//过滤 
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxConditionList = [  { value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}


//提交购箱订单
const handleSubmit = async () => {
  if(!checkval.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》、《用户服务协议和管理规则》') 
  const infoFormValidate = await infoFormRef.value.validate()// 检查 订单信息 必填项
  const validateData = await allocationRef.value.validateData() // 检查 订单分配 必填项
  if (!infoFormValidate || !validateData) {
    ElMessage.warning('订单信息 校验未通过')
    return
  }
  handleSign()
}

// 签署
const handleSign = async () => {
  param.isHandleSigned = true
  const allocation = allocationRef.value.allocation()
  const formData = infoFormRef.value.formData
  const data = {
    "releaseSaleId": rowData.value.id,
    "currency":param.currency || null,
    "unitPrice": param.unitPrice,
    "boxType": param.boxType,
    "boxCondition": param.boxCondition,
    "payCurrency":  param.payCurrency || null,
    "boxQuantity": param.num,
    "planPickupDate": formData.planPickupDate,
    "paymentMethod": formData.paymentMethod - 0,
    "invoiceType": formData.invoiceType - 0,
    "period":  formData.period,
    "contacts": formData.contacts,
    "tel": formData.tel,
    "leaveMsg": formData.leaveMsg,
    "couponAmount": 0,
    "allocation": JSON.stringify(allocation)
  }
  addPurchaseBoxOrder(data).then((res: any) => {
    ElMessage.success('下单成功')
    router.push('agentBuyBox')
  })
  param.dialogVisible = false 
}




//校验
const validateNumber = () => {
  if (!param.num) { param.num = 1 }
}


const rulesInfo = reactive({
  dialogRules:false,
  rules1:false,
  rules2:false
})
const showRules = (val:number) => {  // 显示阅读业务规则
  rulesInfo.dialogRules = true
  rulesInfo.rules1 = false
  rulesInfo.rules2 = false
  switch (val) {
    case 1:
      rulesInfo.rules1 = true
      break;
    case 2:
      rulesInfo.rules2 = true
      break;
  }

}

</script>
<style lang="scss" scoped>
.pag-container {
  margin-top: 20px;
  box-sizing: border-box;
  padding: 10px;
}
.msgLeft tr > td:first-child{
    width: 15%;
    text-align: justify;
    text-align-last: justify;
    padding-right: 10px;
  }
</style>